<template>
  <el-card>
    <el-form label-width="120px" :model="addForm" :rules="formRules" ref="addForm">
      <el-form-item label="属性名" prop="specsname">
        <el-input placeholder="请输入属性名" v-model="addForm.specsname"></el-input>
      </el-form-item>
      <el-form-item label="属性值" prop="attrs">
        <div v-for="(item,index) in attrList" :key="index">
          <el-input v-model="attrList[index].value" placeholder="请输入属性值"></el-input>
          <el-button v-if="index==0" type="primary" @click="addAttr">添加</el-button>
          <el-button v-else type="danger" @click="removeAttr(index)">移除</el-button>
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="addForm.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('addForm')">立即修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  data() {
    // 自定义表单元素校验规则
    const attrValid = (rules, value, callback) => {
      let flag = true;
      this.attrList.forEach(element => {
        if (element.value == "") {
          flag = false;
        }
      });
      if (!flag) {
        return callback(new Error("请填写属性值"));
      }
      callback();
    };
    return {
      addForm: {
        id: this.$route.params.id,
        specsname: "", // 规格名称
        attrs: "", // 属性值
        status: 1 // 状态
      },
      formRules: {
        specsname: { required: true, message: "请输入属性名", trigger: "blur" },
        status: { required: true, message: "请输选择状态", trigger: "blur" },
        attrs: { validator: attrValid, trigger: "blur" }
      },
      attrList: [{ value: "" }]
    };
  },
  methods: {
    addAttr() {
      if (this.attrList.length >= 5) {
        return this.$error("最多只能添加5个");
      }
      this.attrList.push({ value: "" });
    },
    removeAttr(index) {
      this.attrList.splice(index, 1);
    },
    // 获取规格信息
    async getSpecs() {
      const res = await this.$http.get(`/api/specsinfo?id=${this.addForm.id}`);
      if (res.code == 200) {
        this.addForm = res.list[0];
        this.attrList = res.list[0].attrs.map(item => {
          return { value: item };
        });
      }
    },
    // 提交表单
    async submitForm(form) {
      this.$refs[form].validate(async valid => {
        if (valid) {
          // 提交数据
          this.addForm.attrs = this.attrList.map(item => item.value).join(",");
          const res = await this.$http.post("/api/specsedit", this.addForm);
          if (res.code == 200) {
            this.$success("修改成功");
          } else {
            this.$error("修改失败");
          }
        } else {
          console.log("表单校验不通过");
        }
      });
    }
  },
  created() {
    this.getSpecs();
  }
};
</script>

<style>
.el-input {
  width: 300px;
  margin-bottom: 4px;
}
</style>